import json

from django.core.paginator import Paginator
from django.http import HttpResponseForbidden
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.utils import timezone
from django.views import View
from django_redis import get_redis_connection

from goods import utils
from goods.models import GoodsCategory, SKU, GoodsVisitCount
from goods.utils import get_location, get_ip


class ListView(View):
    def get(self, request, category_id, page_num):

        sort = request.GET.get('sort', 'default')
        if sort == 'price':
            sort_key = '-price'
        elif sort == 'hot':
            sort_key = '-sales'
        else:
            sort_key = '-create_time'

        data = utils.get_categories()
        # 面包屑,三级分类
        breadcrumb = GoodsCategory.objects.get(id=category_id)
        skus = SKU.objects.filter(category_id=category_id).order_by(sort_key)

        p = Paginator(skus, 5)
        # 当前页面
        current_page = p.page(page_num)
        # 当前页对象
        current_skus = current_page.object_list
        # 总页数
        total_page = p.num_pages

        context = {
            'categories': data,
            'breadcrumb': breadcrumb,
            "skus_page": current_skus,
            'current_page': page_num,
            'total_page': total_page,
            'category': breadcrumb,
            'sort': sort
        }
        return render(request, 'list.html', context=context)


class HotView(View):
    def get(self, request, category_id):
        # 1.接收数据

        # 2.检验数据

        # 3.处理业务
        # skus_list = []
        # skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by('-sales')[0:2]
        # for sku in skus:
        #     sku_data = {
        #         'id': sku.id,
        #         'name': sku.name,
        #         'price': sku.price,
        #         'default_image_url': sku.default_image_url
        #     }
        #     skus_list.append(sku_data)
        # res = {
        #     'code': 0,
        #     'errmsg': '成功',
        #     'hot_skus': skus_list
        # }
        #
        # # 4.返回响应
        # return JsonResponse(res)
        skus = SKU.objects.filter(category_id=category_id, is_launched=True).order_by('-sales')[0:2]

        skus_list = []

        for sku in skus:
            sku_data = {
                'id': sku.id,
                'name': sku.name,
                'price': sku.price,
                'default_image_url': sku.default_image_url.url
            }
            skus_list.append(sku_data)

        # 4, 返回响应
        res = {
            'code': 0,
            'errmsg': '成功',
            'hot_skus': skus_list
        }

        return JsonResponse(res)


class DetailView(View):
    def get(self, request, sku_id):
        # 频道
        data = utils.get_categories()
        # 面包屑
        # SKU获取
        sku = SKU.objects.get(id=sku_id)
        category_id = sku.category_id
        breadcrumb = GoodsCategory.objects.get(id=category_id)
        # 构建当前商品的规格键
        sku_specs = sku.specs.order_by('spec_id')
        sku_key = []
        for spec in sku_specs:
            sku_key.append(spec.option.id)
        # 获取当前商品的所有SKU
        skus = sku.spu.sku_set.all()
        # 构建不同规格参数（选项）的sku字典
        spec_sku_map = {}
        for s in skus:
            # 获取sku的规格参数
            s_specs = s.specs.order_by('spec_id')
            # 用于形成规格参数-sku字典的键
            key = []
            for spec in s_specs:
                key.append(spec.option.id)
            # 向规格参数-sku字典添加记录
            spec_sku_map[tuple(key)] = s.id
        # 获取当前商品的规格信息
        goods_specs = sku.spu.specs.order_by('id')
        # 若当前sku的规格信息不完整，则不再继续
        if len(sku_key) < len(goods_specs):
            return
        for index, spec in enumerate(goods_specs):
            # 复制当前sku的规格键
            key = sku_key[:]
            # 该规格的选项
            spec_options = spec.options.all()
            for option in spec_options:
                # 在规格参数sku字典中查找符合当前规格的sku
                key[index] = option.id
                option.sku_id = spec_sku_map.get(tuple(key))
            spec.spec_options = spec_options
        # =======额外功能==========
        # 实现检索ip获取地址
        # ip = get_ip(request)
        # location = get_location(ip)

        context = {
            'categories': data,
            'breadcrumb': breadcrumb,
            'sku': sku,
            'specs': goods_specs,
            # 'location':location
        }
        return render(request, 'detail.html', context=context)


class DetailVisitView(View):
    def post(self, request, category_id):
        current_date = timezone.localdate()
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except Exception as e:
            return HttpResponseForbidden('分类id不存在')
        try:
            visit_count = GoodsVisitCount.objects.get(category=category, date=current_date)
            visit_count.count += 1
            visit_count.save()
        except Exception as e:
            GoodsVisitCount.objects.create(category=category, count=1, date=current_date)
        res = {
            'code': 0,
            'data': '成功'
        }

        return JsonResponse(res)


class BrowseHistoryView(View):
    def post(self, request):

        # 1.接收数据
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        # 2.检验数据
        user = request.user
        if not user.is_authenticated:
            return JsonResponse({'code': 9999, 'errmsg': '未登录'})
        try:
            SKU.objects.get(id=sku_id)
        except Exception as e:
            return JsonResponse({'data': '商品不存在'})
        # 3.处理业务
        redis_client = get_redis_connection('history')
        # 去重
        history = redis_client.lrange('history_%s' % user.id, 0, -1)
        if history:
            redis_client.lrem('history_%s' % user.id, 0, sku_id)
        # 推到首位
        redis_client.lpush('history_%s' % user.id, sku_id)
        # 截取前5个
        redis_client.ltrim('history_%s' % user.id, 0, 4)
        # 4.返回响应
        res = {
            'code': 0,
            'errmsg': '成功'
        }
        return JsonResponse(res)
